package server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

// [类的加载（加载.class文件或者jar包中的类） - 简书](https://www.jianshu.com/p/451950fdf384)
public class MyClassLoader extends ClassLoader {

    protected Class<?> findClass(String dir) throws ClassNotFoundException {
        File classFile = new File(dir);
        if (!classFile.exists()) {
            throw new ClassNotFoundException(classFile.getPath() + " 不存在");
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ByteBuffer bf = ByteBuffer.allocate(1024);
        try (FileInputStream fis = new FileInputStream(classFile);
             FileChannel fc = fis.getChannel()) {
            while (fc.read(bf) > 0) {
                bf.flip();
                bos.write(bf.array(), 0, bf.limit());
                bf.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass(bos.toByteArray(), 0, bos.toByteArray().length);
    }

    public static void main(String[] args) throws Exception {
        MyClassLoader mcl = new MyClassLoader();
        Class<?> personClass = mcl.findClass("D:\\t\\lagou\\practice\\practice-tomcat\\webapps\\demo1\\servlet\\LagouServlet1.class");
        Object person = personClass.newInstance();
        System.out.println(person);
        System.out.println(person instanceof HttpServlet);
    }
}
